#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <errno.h>

#define N 32
#define ERRLOG(errmsg) do{\
                                                            perror(errmsg);\
                                                            printf("file:%s,func:%s,line:%d\n",__FILE__,__func__,__LINE__);\
                                                            exit(-1);\
                                                            }while(0);

int main(int argc, char const *argv[])
{
    if(argc != 3){
        ERRLOG("argc is invalid");
    }

    int sockfd=-1;
    int acceptfd=-1;
    struct sockaddr_in servaddr,clientaddr;
    socklen_t addrlen=sizeof(servaddr);

    if((sockfd=socket(AF_INET,SOCK_DGRAM,0))==-1){
        ERRLOG("socket error");
    }

    memset(&servaddr,0,addrlen);
    servaddr.sin_family=AF_INET;
    servaddr.sin_addr.s_addr=inet_addr(argv[1]);
    servaddr.sin_port=htons(atoi(argv[2]));

    if(bind(sockfd,(struct sockaddr*)&servaddr,addrlen)==-1){
        ERRLOG("bind error");
    }

    char buf[N]={0};

    while(1){
        if(recvfrom(sockfd,buf,N,0,(struct sockaddr*)&clientaddr,&addrlen)==-1){
            ERRLOG("recvfrom error");
        }

        printf("buf=%s\n",buf);
        strcat(buf,"^_^");

        if(sendto(sockfd,buf,N,0,(struct sockaddr*)&clientaddr,addrlen)==-1){
            ERRLOG("sendto error");
        }
    }
    
    return 0;
}

